const express=require('express');

var router = express.Router();
// const path = require('path'); 

// 中间件
// router.use(express.urlencoded({extended:false}));
// router.use(express.json());

// 引入 myquery
const myquery = require('../routes/myquery')
//引入cors



// 注册
router.post('/register',async (req,res,next)=>{
    // 接参
   console.log(req.body);
   let {username,password} = req.body;

    // 判断用户名和密码是否为空
    if(!username || !password){
        next('用户名或密码不能为空');
        return;
    }

    // 运行sql语句，判断用户名是否存在
    let sql = `select * from haha where username = '${username}'`;
    let [err,result] = await myquery(sql);

    if(err){
        next(err);
        return;
    }   
    // 已存在
    if(result.length > 0){
        next('用户名已存在');
        return;
    }
    // 不存在就添加用户信息到表中
    let sql1 = `insert into haha (username,password) values ('${username}','${password}')`;

    let [err1,result1] = await myquery(sql1);

    if(err1){
        next(err1);
        return;
    }

    if(result1.insertId > 0){
        res.send({code:200,msg:'注册成功'})
    }else{
        next('请稍后再试')
    }
   

})



//登录
router.post('/login',async (req,res,next)=>{
    // 接参
   //console.log(req.body);
   let {username,password} = req.body;

    // 判断用户名和密码是否为空
    if(!username || !password){
        next('用户名或密码不能为空');
        return;
    }

    // 运行sql语句，判断用户名是否存在
    let sql = `select * from haha where username = '${username}' and password='${password}'`;
    let [err,result] = await myquery(sql);
    console.log(await myquery(sql));

    if(err){
        next(err);
        return;
    }   
    // 已存在
    if(result.length > 0){
       res.send('登陆成功');
       
    }else{
        next('用户名或密码不正确')
        return;
    }
  

})



module.exports = router;
